package com.example.controller;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.example.entity.LoginParams;
import com.example.entity.SmsParams;
import com.example.exception.BaseException;
import com.example.model.api.Result;
import com.example.redis.RedisUtils;
import com.example.service.CaptchaService;
import com.example.service.PhoneCodeService;
import com.example.validator.AssertUtils;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@Tag(name = "app登录接口")
public class LoginController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private PhoneCodeService phoneCodeService;

    @Autowired
    private RedisUtils redisUtils;

    @PostMapping("/user/login/username")
    @Operation(summary = "用户名密码登录")
    public Result<String> login(@RequestBody LoginParams loginParams) {
        return Result.success("ok");
    }
    @PostMapping("/user/login/sms")
    @Operation(summary = "手机号快速登录")
    public Result<String> login(@RequestBody SmsParams smsParams) {
        return Result.success("ok");
    }

    @GetMapping("captcha")
    @Operation(summary = "随机验证码")
    public void captcha(HttpServletResponse response, @RequestParam("uuid") String uuid) throws IOException {
        //uuid不能为空
        AssertUtils.isBlank(uuid, "uuid不能为空");

        //生成验证码
        captchaService.create(response, uuid);
    }


    @GetMapping("phoneCode")
    @Operation(summary = "发送手机短信验证码")
    public Result<String> sendMsmCode(@RequestParam("phone") String phone) {
        // 手机号格式校验（可选）
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return Result.fail("手机号格式不正确");
        }

        // 1. 判断是否已经有验证码正在生效（防止重复发送）
        String codeKey = "phoneCode:" + phone;
        if (Boolean.TRUE.equals(redisUtils.hasKey(codeKey))) {
            return Result.fail("验证码已发送，请注意查收");
        }

        // 2. 获取发送次数并判断是否超过限制（1小时最多10次）
        String countKey = "phoneCode:sendCount:" + phone;
        if (redisUtils.incrementSendCount(countKey, 10, 3600)) {
            return Result.fail("该手机号一小时内发送验证码已达上限");
        }

        // 3. 第一次发送或未达上限时生成验证码
        String codeValue = phoneCodeService.generateVerificationCode(6);
        boolean setResult = redisUtils.setIfNotExists(codeKey, codeValue, 60); // 验证码有效期60秒
        if (!setResult) {
            return Result.fail("系统异常，请稍后再试");
        }

        // 4. 发送短信
        try {
            phoneCodeService.sendMsgCode(phone, codeValue);
        } catch (Exception e) {
            redisUtils.delete(codeKey);
            redisUtils.delete(countKey);
            throw new BaseException("短信发送失败：" + e.getMessage());
        }

        return Result.success("发送短信成功");
    }


}
